import Vue from 'vue'
import App from './App.vue'
import router from './router'
import { 
  registerMicroApps, 
  start, 
  setDefaultMountApp,
  addGlobalUncaughtErrorHandler,
  initGlobalState,
  prefetchApps
} from 'qiankun'

Vue.config.productionTip = false

// 定义全局状态
const initialState = {
  user: {
    name: '主应用用户',
    role: 'admin'
  },
  theme: 'light'
}

// 初始化全局状态
const actions = initGlobalState(initialState)

// 监听全局状态变化
actions.onGlobalStateChange((state, prev) => {
  console.log('主应用：全局状态发生变化', state, prev)
})

// 设置默认加载的子应用
setDefaultMountApp('/vue2-sub-app1')

// 预加载子应用
prefetchApps([
  { name: 'vue2-sub-app1', entry: '//localhost:8081' },
  { name: 'vue2-sub-app2', entry: '//localhost:8082' }
])

// 注册子应用
registerMicroApps([
  {
    name: 'vue2-sub-app1',
    entry: '//localhost:8081',
    container: '#subapp-viewport',
    activeRule: '/vue2-sub-app1',
    props: {
      // 传递给子应用的数据
      mainAppData: {
        title: '来自主应用的数据',
        timestamp: Date.now()
      },
      // 传递给子应用的方法
      mainAppMethods: {
        showMessage: (msg) => {
          console.log('主应用收到消息:', msg)
        }
      }
    }
  },
  {
    name: 'vue2-sub-app2',
    entry: '//localhost:8082',
    container: '#subapp-viewport',
    activeRule: '/vue2-sub-app2',
    props: {
      mainAppData: {
        title: '来自主应用的数据',
        timestamp: Date.now()
      },
      mainAppMethods: {
        showMessage: (msg) => {
          console.log('主应用收到消息:', msg)
        }
      }
    }
  }
], {
  // 生命周期钩子
  beforeLoad: [
    app => console.log('子应用加载前', app.name)
  ],
  beforeMount: [
    app => console.log('子应用挂载前', app.name)
  ],
  afterMount: [
    app => console.log('子应用挂载后', app.name)
  ],
  beforeUnmount: [
    app => console.log('子应用卸载前', app.name)
  ],
  afterUnmount: [
    app => console.log('子应用卸载后', app.name)
  ]
})

// 添加全局未捕获异常处理
addGlobalUncaughtErrorHandler((event) => {
  console.error('全局异常:', event)
})

// 启动 qiankun
start({
  sandbox: {
    // 开启沙箱
    strictStyleIsolation: true, // 开启严格的样式隔离
    experimentalStyleIsolation: true // 开启实验性的样式隔离
  },
  singular: true, // 是否为单实例模式
  prefetch: 'all' // 预加载策略：all-预加载所有子应用
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app') 